﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Caliburn.Micro;
using NMortgage.UI.Events;
using NMortgage.UI.Model;

namespace NMortgage.UI.ViewModels
{
    public abstract class ABaseItemListViewModel<TCollection,KEntity> : BaseViewModel, IHandle<ProfileItemAdded>, IHandle<CancelEvent>
        where TCollection : AEntityBaseCollection<KEntity>
        where KEntity : class
    {
        #region Fields

        private readonly IEventAggregator eventAggregator;

        private object dialogViewModel;

        #endregion Fields

        #region Constructors
        protected ABaseItemListViewModel() { }
        public ABaseItemListViewModel(IEventAggregator eventAggregator)
        {
            this.eventAggregator = eventAggregator;
            this.eventAggregator.Subscribe(this);
        }

        #endregion Constructors

        #region Properties
        
        protected IEventAggregator EventAggregator {
            get { return eventAggregator; }
        }

        public object ItemDialog
        {
            get { return dialogViewModel; }
            protected set
            {
                dialogViewModel = value;
                NotifyOfPropertyChange(() => ItemDialog);
            }
        }

        public TCollection ItemCollection
        {
            get;
            protected set;
        }

        #endregion Properties

        #region Methods

        public abstract void Add();

        public abstract void Edit(KEntity item);

        public void Handle(ProfileItemAdded message)
        {
            if (message != null)
            {
                var item = message.Item as KEntity;

                if (item != null)
                {
                    ItemCollection.Add(item);
                }

                if (ItemDialog != null) { ItemDialog = null; }
            }
        }

        public void Handle(CancelEvent message)
        {
            if (ItemDialog != null && message.Source.GetType() == ItemDialog.GetType())
            {
                ItemDialog = null;
            }
        }

        public void MoveDown(KEntity item)
        {
            ItemCollection.MoveDown(item);
        }

        public void MoveUp(KEntity item)
        {
            ItemCollection.MoveUp(item);
        }

        public void Remove(KEntity item)
        {
            ItemCollection.Remove(item);
        }

        #endregion Methods
    
    }
}
